package org.wsocket.thread;

import java.io.IOException; 
import java.nio.channels.SocketChannel;
import java.util.Map;
import java.util.Random;

import org.apache.log4j.Logger;
import org.wsocket.WSocket;
import org.wsocket.connector.Connector;
import org.wsocket.protocol.SocketHandler;
import org.wsocket.socketset.SocketSet;

/** 
 * @author alvin
 */
public class HandShakeMessageTask implements ThreadTask {
    private int status = 0;

    private SocketChannel taskData = null;

    private static Logger log=Logger.getLogger(HandShakeMessageTask.class);
    public HandShakeMessageTask(SocketChannel taskData) {
        this.status = ThreadTask.NOT_STARTED;
        this.taskData = taskData;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;

    }

	public void run() {
		Random random = new Random();
		try {
			Map<String, String> handShakeRetMap = SocketHandler
					.processHandshake(taskData);
			if (handShakeRetMap == null) {
				taskData = null;
				return;
			}
			taskData.configureBlocking(false);
			String currentSet = random.nextInt(WSocket.getAllSocketSetSize())
					+ "";
			Connector newConnector = new Connector(taskData, currentSet);
			newConnector.setAuthKey(handShakeRetMap
					.get(SocketHandler.KEY_PARAM));
			((SocketSet) (WSocket.getAllSocketSets().get(currentSet)))
					.addConnector(newConnector);
		} catch (IOException e) {
			log.error(e);
		} 
	}
}
